#pragma once

#include <map>
#include <algorithm>
#include "Precious.h"

typedef std::map< CPrecious::PID,CPrecious* > MAP_PRECIOUS;

class CPreciousManager
	: public MAP_PRECIOUS
{
public:
	CPreciousManager(void);
	~CPreciousManager(void);

	static const CPrecious::PID PID_AU = 1; 
	static const CPrecious::PID PID_AG = 2; 
	static const CPrecious::PID PID_PD = 3; 

	void Insert( CPrecious::PID nID, CPrecious* pPrecious, bool bUpdate = true );
	void Clear( void );

	static CPrecious* PreciousFactory( CPrecious::PID, const tstring& strFile, int nElapse, bool bWrap );

private:
	static void DeleteOne( MAP_PRECIOUS::value_type& vtValue );
};

inline CPreciousManager::CPreciousManager(void)
{
	;
}

inline CPreciousManager::~CPreciousManager(void)
{
	Clear();
}

inline void CPreciousManager::DeleteOne( MAP_PRECIOUS::value_type& vtValue )
{
	delete vtValue.second;
	vtValue.second = NULL;
}

inline void CPreciousManager::Clear( void )
{
	std::for_each( begin(), end(), DeleteOne );
	clear();
}

inline CPrecious* CPreciousManager::PreciousFactory( CPrecious::PID nID, const tstring& strFile, int nElapse, bool bWrap )
{
	switch( nID )
	{
	case PID_AU:
		{
			CPrecious* pAU = new CPrecious( nID, _T("XAUUSD") );
			pAU->SetLogFile( strFile );
			pAU->SetElapse( nElapse );
			pAU->SetWrap( bWrap );
			return pAU;
		}
	case PID_AG:
		{
			CPrecious* pAG = new CPrecious( nID, _T("XAGUSD") );
			pAG->SetLogFile( strFile );
			pAG->SetElapse( nElapse );
			pAG->SetWrap( bWrap );
			return pAG;
		}
	case PID_PD:
		{
			CPrecious* pPD = new CPrecious( nID, _T("XPDUSD") );
			pPD->SetLogFile( strFile );
			pPD->SetElapse( nElapse );
			pPD->SetWrap( bWrap );
			return pPD;
		}
	default:
		{
			ASSERT( FALSE );
			return NULL;
		}
	}
}

inline void CPreciousManager::Insert( CPrecious::PID nID, CPrecious* pPrecious, bool bUpdate /*= true */)
{
	iterator iter = find( nID );
	if( iter != end() && bUpdate )
	{
		if( bUpdate )
		{
			DeleteOne( *iter );
		}
		else
		{
			return ;
		}
	}

	insert( value_type(nID, pPrecious) );
}